package com.rainsoftware.LicenseSystem.inertceptor;

import com.rainsoftware.LicenseSystem.models.entity.SystemUser;
import com.rainsoftware.LicenseSystem.services.UserService;
import com.rainsoftware.LicenseSystem.utils.StandardResponse;
import io.jsonwebtoken.ExpiredJwtException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.List;

public class JWTInterceptor implements HandlerInterceptor {

    private final UserService userService;

    public JWTInterceptor(UserService userService) {
        this.userService = userService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        if (token != null) {
            token = token.replace("Bearer ", "");
            try {
                try {
                    SystemUser user = userService.parseUser(token);
                    if (user == null) {
                        UserService.generateResponse(response, new StandardResponse(false, HttpStatus.NOT_FOUND, "用户不存在"));
                        return false;
                    } else {
                        String role = user.getRole(); // Assuming SystemUser has a getRole() method
                        if (!isAuthorized(request.getRequestURI(), role)) {
                            UserService.generateResponse(response, new StandardResponse(false, HttpStatus.FORBIDDEN, "权限不足"));
                            return false;
                        }
                    }
                } catch (ExpiredJwtException e) {
                    UserService.generateResponse(response, new StandardResponse(false, 50014, "JWT过期"));
                    return false;
                }
            } catch (RuntimeException e) {
                e.printStackTrace();
                UserService.generateResponse(response, new StandardResponse(false, HttpStatus.INTERNAL_SERVER_ERROR, "服务器错误"));
                return false;
            }
        } else {
            UserService.generateResponse(response, new StandardResponse(false, HttpStatus.BAD_REQUEST, "Token 错误"));
            return false;
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }

    private boolean isAuthorized(String uri, String role) {
        // Define role-based access rules
        List<String> adminEndpoints = List.of(
                "/api/keypairs",
                "/api/license-keys/.*",
                "/api/product");
        List<String> userEndpoints = List.of(
                "/api/keypairs",
                "/api/license-keys/.*",
                "/api/license-keys",
                "/api/user/.*",
                "/api/product");
        if (!adminEndpoints.stream().anyMatch(uri::matches) && "Admin".equals(role)) {
            return false;
        }
        if (!userEndpoints.stream().anyMatch(uri::matches) && "Developer".equals(role)) {
            return false;
        }
        return true;
    }
}
